package com.grayscale.core.config;

import com.grayscale.core.util.GrayScalePathBuilder;
import com.grayscale.core.util.HostUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.annotation.Resource;

/**
 * @author liuli
 * @date 2022/2/9
 * 服务节点注册
 * 1、注册服务节点（注册服务）
 * 2、创建本地服务文件路径（存在不处理）
 */
@Configuration
public class GrayScaleServiceNodeRegister {
    private Logger log = LoggerFactory.getLogger(this.getClass());
    @Resource
    GrayScaleClientConfig grayScaleClientConfig;
    @Resource
    GrayScaleZookeeper grayScaleZookeeper;



    @Bean
    public void register() {
        if (!grayScaleClientConfig.needRegister()){
            return ;
        }
        log.info("Grayscale OfflinePath：{}",grayScaleClientConfig.getOfflinePath());
        if (grayScaleClientConfig.getOfflineMode()){
            log.warn("Grayscale 开启离线模式,所有配置读取本地");
        }
        String localHost = HostUtil.getLocalHost()+":"+grayScaleClientConfig.getServerPort();
        try {
            //注册服务
            String hostDir = GrayScalePathBuilder.buildAppNodePath(grayScaleClientConfig.getAppName(),grayScaleClientConfig.getAppCode(), localHost);
            grayScaleZookeeper.createTempNode(hostDir,localHost);
            log.info("Register Client-》{} {} Success", grayScaleClientConfig.getAppCode(), localHost);
            String serverPath = GrayScalePathBuilder.buildAppPath(grayScaleClientConfig.getAppName(),grayScaleClientConfig.getAppCode());
            grayScaleZookeeper.treeCacheListen(serverPath);
        } catch (Exception e) {
            log.error("Register Client-》{} {} Exception {}", grayScaleClientConfig.getAppCode(), localHost, e);
        }
    }

}
